import axios from 'axios'
import { getServerBaseURL } from '@/config'
import { Toast } from 'antd-mobile'
import { stores } from '@/stores'
import { axiosInterceptorFilterEmptyData, axiosInterceptorRefreshToken } from 'train-fe-component'
import { roleHistory } from '@/routes/roleHistory'
import { getXSiteDomain } from './helper'
import type { AxiosRequestConfig, AxiosResponse } from 'axios'
import type { HttpResponse } from './interface'
import { refreshToken } from '@/api/base'

export const http = axios.create({
    baseURL: getServerBaseURL(true),
    headers: {
        'Content-Type': 'application/json',
        // 'X-Site-Domain': location.host,
        'X-Site-Domain': getXSiteDomain(),
    },

    /** 处理 */
    validateStatus: status => {
        return (status >= 200 && status < 300) || status === 401
    },
})

/**
 * 添加 token
 */
http.interceptors.request.use((config: AxiosRequestConfig) => {
    if (stores.userStore.isLogin) {
        const token =
            config.url === '/oauth/refresh-token'
                ? stores.userStore.getRefreshToken
                : stores.userStore.getAccessToken

        config.headers = {
            ...config.headers,
            Authorization: 'Bearer ' + token,
        }
    }

    return config
})

/**
 * 过滤params对象中空字符串字段
 */
http.interceptors.request.use(
    axiosInterceptorFilterEmptyData({
        methodList: ['get'],
    }),
)

http.interceptors.response.use(
    (res: AxiosResponse<HttpResponse>) => {
        // 正常http状态码
        if (![0, 200].includes(res.data.code)) {
            Toast.show({
                icon: 'fail',
                content: res.data.msg,
            })
            return Promise.reject(res.data.msg)
        }

        if (res.status !== 401) {
            return res
        } else {
            // refreshToken 超时，重新登录
            if (res.config.url === '/oauth/refresh-token') {
                Toast.show({
                    icon: 'fail',
                    content: '登录状态过期，请重新登录',
                })
                stores.userStore.logout(false)
                roleHistory.replace('/login')
                return Promise.reject()
            }

            // accessToken过期，刷新
            return axiosInterceptorRefreshToken(res, {
                // axios实例
                instance: http,
                // 从服务器中获取刷新令牌
                refresh: () => {
                    return refreshToken().then(({ data }) => {
                        stores.userStore.updateAccessToken(data.access_token)

                        return data.access_token
                    })
                },
            })
        }
    },
    error => {
        const res = error?.response
        const httpCode = res.status
        const msg = res?.data.msg

        // http状态码异常
        if (httpCode > 204 || httpCode < 200) {
            Toast.show({
                icon: 'fail',
                content: msg,
            })
        }

        return Promise.reject(error)
        // return new Promise(() => {})
    },
)

http.interceptors.response.use((res: AxiosResponse) => {
    const processRes = { ...res, ...res.data }
    return processRes
})
